//
//  ACBase.m
//  AlarmClock
//
//  Created by kai ren on 24/10/2011.
//  Copyright 2011 none. All rights reserved.
//

#import "ACBase.h"

/** Get the full path of document **/
NSString *getDocumentPath(){
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	
	return documentsDirectory;
}

NSArray *getContentsOfDocument(){
	NSFileManager *fileManger = [[NSFileManager alloc] init];
	NSArray *contents = [fileManger contentsOfDirectoryAtPath:getDocumentPath() error:nil];
	
	[fileManger release];
	
	return contents;
}

/** Get the full path of cache key **/
NSString *getFileFullPath(NSString *fileName){
	if (nil == fileName) {
		return nil;
	}
	
	NSString *documentsDirectory  = getDocumentPath();
	
	if (nil == documentsDirectory) {
		return nil;
	}
	
	return [documentsDirectory stringByAppendingPathComponent:fileName];
}

/** delete afile **/
void deleteFile(NSString *fileName){
	NSString *filePath = getFileFullPath(fileName);
	NSError *err = nil;
	
	if (nil == fileName) {
		return;
	}
	
	NSFileManager *appFileManager = [NSFileManager defaultManager];
	
	if (![appFileManager fileExistsAtPath:filePath]) {
		return;
	}
	
	if (![appFileManager isDeletableFileAtPath:filePath]) {
		return;
	}
	
	[appFileManager removeItemAtPath:filePath error:&err];
}

NSString *stringOfRepeat(ACAlarm *alarm){
	NSMutableString *str = [NSMutableString stringWithCapacity:0];
	
	if (1111111 == alarm.repeat) {
		return NSLocalizedString(@"Every day", nil);
	} else if (111110 == alarm.repeat) {
		return NSLocalizedString(@"Weekdays", nil);
	} else if (1000001 == alarm.repeat) {
		return NSLocalizedString(@"Weekends", nil);
	} else if (0 == alarm.repeat) {
		return NSLocalizedString(@"Never", nil);
	}
	
	int intRepeat = alarm.repeat/10;
	NSArray *days = [NSArray arrayWithObjects:
					 NSLocalizedString(@"Sun ", nil),
					 NSLocalizedString(@"Mon ", nil),
					 NSLocalizedString(@"Tue ", nil),
					 NSLocalizedString(@"Wed ", nil),
					 NSLocalizedString(@"Thu ", nil),
					 NSLocalizedString(@"Fri ", nil),
					 NSLocalizedString(@"Sat ", nil),
					 nil];
	
	for (int i = 1; i <= 6; i++) {
		if (intRepeat%10 == 1) {
			[str appendString:[days objectAtIndex:i]];
		}
		intRepeat = intRepeat/10;
	}
	
	if (alarm.repeat%10 == 1) {
		[str appendString:[days objectAtIndex:0]];
	}
	
	return [str substringToIndex:[str length] - 1];
}

/** status network activity indicator counter **/
static NSInteger _NetworkActivityIndicatorCounter = 0;

/** show status activity indicator **/
void showNetworkActivityIndicator() {
	_NetworkActivityIndicatorCounter++;
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}

/** hidden status activity indicator **/
void hideNetworkActivityIndicator() {
	_NetworkActivityIndicatorCounter--;
	[UIApplication sharedApplication].networkActivityIndicatorVisible = _NetworkActivityIndicatorCounter > 0;
}